package com.utils.cookie;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

/*
 * 根据Url得到cookie
 */
public class HttpClientCookieUtil {

	public static Cookie[] getCookies(String url) {
		HttpClient client = new HttpClient();
		client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler(3, false));

		GetMethod method = new GetMethod(url);
		try {
			client.executeMethod(method);
			Cookie[] cookies = client.getState().getCookies();
			return cookies;
		} catch (Exception e) {
			System.err.println(e);
		} finally {
			method.releaseConnection();
		}
		return null;
	}

	public static void main(String args[]) throws Exception {
		HttpClient client = new HttpClient();
		client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler(3, false));

		GetMethod method = new GetMethod("http://localhost:8080/");
		try {
			client.executeMethod(method);
			Cookie[] cookies = client.getState().getCookies();
			for (int i = 0; i < cookies.length; i++) {
				Cookie cookie = cookies[i];
				System.err.println("Cookie: " + cookie.getName() + ", Value: "
						+ cookie.getValue() + ", IsPersistent?: "
						+ cookie.isPersistent() + ", Expiry Date: "
						+ cookie.getExpiryDate() + ", Comment: "
						+ cookie.getComment());
				cookie.setValue("My own value");
			}
			client.executeMethod(method);
		} catch (Exception e) {
			System.err.println(e);
		} finally {
			method.releaseConnection();
		}
	}
}
